/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import doa.MessageDAO;
import doa.TwittererDAO;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import models.Twitterer;
import utils.JSFSessionHandler;

/**
 *
 * @author Misja
 */
public class HomeBean {

    private Twitterer twitterer;

    public HomeBean() {
        this.twitterer = (Twitterer) JSFSessionHandler.getObjectFromSession("currentUser");
    }

    public Twitterer getTwitterer() {
        return twitterer;
    }

    public void setTwitterer(Twitterer twitterer) {
        this.twitterer = twitterer;
    }

    public List<Twitterer> getFavorites() {
        return new ArrayList<Twitterer>(this.twitterer.getFavorites());
    }

    public String readMessages(Twitterer twitterer) {
        JSFSessionHandler.putObjectInSession("selectedUser", twitterer);
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("twitterer", twitterer);
        return "/MessageOverview.xhtml?faces-redirect=true";
    }

    public long postedMessages() {
        return MessageDAO.countMessageByOwner((Twitterer) JSFSessionHandler.getObjectFromSession("currentUser"));
    }

    public void removeFavorite(Twitterer favorite) {
        Twitterer temp = this.twitterer;
        temp.getFavorites().remove(favorite);

        if (TwittererDAO.updateTwitterer(temp)) {
            JSFSessionHandler.putObjectInSession("currentUser", temp);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Twitterer updated", null));
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Twitterer not updated", null));
        }
    }

    public String toTwittererOverView() {
        return "/TwittererOverview.xhtml?faces-redirect=true";
    }

    public String toNewMessage() {
        return "/NewMessage.xhtml?faces-redirect=true";
    }

    public String deleteAccount() {
        if (TwittererDAO.deleteTwitterer((Twitterer) JSFSessionHandler.getObjectFromSession("currentUser"))) {
            JSFSessionHandler.clearSession();
            return "/Login.xhtml?faces-redirect=true";
        }
        return null;
    }

    public String upgradeAccount() {
        Twitterer tmpTwitterer = (Twitterer) JSFSessionHandler.getObjectFromSession("currentUser");
        tmpTwitterer.setPlatinumTwitterer(true);
        if (TwittererDAO.updateTwitterer(tmpTwitterer)) {
            JSFSessionHandler.putObjectInSession("currentUser", tmpTwitterer);
        }
        return "/Home.xhtml?faces-redirect=true";
    }
}
